//package com.scs.application.modules.sys.schedule;
//
//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
//import com.baomidou.mybatisplus.core.toolkit.Wrappers;
//import com.scs.application.consts.GlobalConsts;
//import com.scs.application.consts.SerialKeys;
//import com.scs.application.core.utils.StringUtils;
//import com.scs.application.modules.base.entity.Dept;
//import com.scs.application.modules.base.entity.Warehouse;
//import com.scs.application.modules.base.service.DeptService;
//import com.scs.application.modules.base.service.WarehouseService;
//import com.scs.application.modules.dept.entity.Apply;
//import com.scs.application.modules.dept.entity.ApplyAuto;
//import com.scs.application.modules.dept.entity.ApplyItem;
//import com.scs.application.modules.dept.service.ApplyAutoService;
//import com.scs.application.modules.dept.service.ApplyItemService;
//import com.scs.application.modules.dept.service.ApplyService;
//import com.scs.application.modules.finance.entity.Bill;
//import com.scs.application.modules.finance.entity.BillItem;
//import com.scs.application.modules.finance.service.BillItemService;
//import com.scs.application.modules.finance.service.BillService;
//import com.scs.application.modules.sys.adapter.SerialRuleAdapter;
//import com.scs.application.modules.wm.entity.Stock;
//import com.scs.application.modules.wm.entity.WorkOrder;
//import com.scs.application.modules.wm.entity.WorkOrderItem;
//import com.scs.application.modules.wm.enums.WorkOrderType;
//import com.scs.application.modules.wm.service.StockService;
//import com.scs.application.modules.wm.service.WorkOrderItemService;
//import com.scs.application.modules.wm.service.WorkOrderService;
//import com.google.common.collect.Lists;
//import lombok.AllArgsConstructor;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.beans.BeanUtils;
//import org.springframework.stereotype.Service;
//import org.springframework.transaction.annotation.Transactional;
//
//import java.time.LocalDateTime;
//import java.util.ArrayList;
//import java.util.Calendar;
//import java.util.List;
//import java.util.stream.Collectors;
//
//@AllArgsConstructor
//@Slf4j
//@Service
//public class AutoMockTask {
//
//    private ApplyService applyService;
//
//    private ApplyAutoService applyAutoService;
//
//    private ApplyItemService applyItemService;
//
//    private DeptService deptService;
//
//    private StockService stockService;
//
//    private WarehouseService warehouseService;
//
//    private SerialRuleAdapter serialRuleAdapter;
//
//    private BillService billService;
//
//    private BillItemService billItemService;
//
//    private WorkOrderService workOrderService;
//
//    private WorkOrderItemService workOrderItemService;
//
//    public void autoOMData() {
//        autoInsertDeptApplys();
//        autoAddBills();
//    }
//
//    //自动添加科室请领
//    @Transactional(rollbackFor = Exception.class)
//    public void autoInsertDeptApplys() {
//        List<Dept> depts = deptService.list(new QueryWrapper<Dept>().isNotNull("warehouse_id"));
//
//        if (depts == null || depts.size() == 0) {
//            return;
//        }
//        Calendar calendar = Calendar.getInstance();
//        calendar.add(Calendar.MONTH, -1);
//        //删除一个月以前的数据
//        applyService.remove(new QueryWrapper<Apply>().gt("gmt_create", calendar.getTime()));
//        applyItemService.remove(new QueryWrapper<ApplyItem>().gt("gmt_create", calendar.getTime()));
//        applyAutoService.remove(new QueryWrapper<ApplyAuto>().gt("gmt_create", calendar.getTime()));
//        depts.forEach(dept -> {
//            applyService.update(Wrappers.<Apply>update()
//                    .eq("dept_id", dept.getId())
//                    .set("flow_status", "end")); //将以前的修改为完成
//
//            Warehouse warehouse = warehouseService.getById(dept.getWarehouseId());
//            if (warehouse != null && StringUtils.isNotBlank(warehouse.getApplyWarehouseId())) {
//                List<Stock> stocks = stockService.list(new QueryWrapper<Stock>().eq("warehouse_id", warehouse.getId()).groupBy("matr_id", "matr_name", "matr_spec", "sku_price", "sku_qty", "sku_unit", "package_qty","package_unit", "amount"));
//                if (stocks != null && stocks.size() > 0) {
//                    Apply apply = new Apply();
//                    List<ApplyItem> applyItems = Lists.newArrayList();
//                    apply.setBusDate(Calendar.getInstance().getTime())
//                            .setBusKey(serialRuleAdapter.getSerialRuleService().generateCode(SerialKeys.DEPT_APPLY_KEY))
//                            .setBusUser("system")
//                            .setDeptId(dept.getId())
//                            .setDeptName(dept.getName())
//                            .setWarehouseId(warehouse.getApplyWarehouseId())
//                            .setWarehouseName(warehouse.getApplyWarehouseName())
//                            .setRemark("系统自动生成")
//                            .setFlowStatus("start");
//                    stocks.forEach(stock -> {
//                        ApplyItem applyItem = new ApplyItem();
//                        BeanUtils.copyProperties(stock, applyItem);
//                        applyItem.setId(null);
//                        applyItem.setMatrId(stock.getMatrId())
//                                .setMatrName(stock.getMatrName())
//                                .setMatrSpec(stock.getMatrSpec())
//                                .setSkuPrice(stock.getSkuPrice())
//                                .setSkuQty(stock.getSkuQty())
//                                .setPackageRate(1d)
//                                .setPackageUnit(stock.getPackageUnit())
//                                .setPackageQty(1d)
//                                .setAmount(stock.getAmount())
//                                .setSkuUnit(stock.getSkuUnit());
//                        applyItems.add(applyItem);
//                    });
//                    apply.setAmount(applyItems.stream().mapToDouble(ApplyItem::getAmount).sum());
//                    boolean result = applyService.save(apply);
//                    if (result) {
//                        applyItems.forEach(applyItem -> applyItem.setApplyId(apply.getId()));
//                        applyItemService.saveBatch(applyItems);
//
//                        List<ApplyAuto> applyAutos = Lists.newArrayList();
//                        applyItems.forEach(applyItem -> {
//                            ApplyAuto applyAuto = new ApplyAuto();
//                            BeanUtils.copyProperties(applyItem, applyAuto);
//                            applyAuto.setId(null);
//                            applyAuto.setSkuQtyStock(applyItem.getSkuQty())
//                                    .setWarehouseId(apply.getWarehouseId())
//                                    .setWarehouseName(apply.getWarehouseName())
//                                    .setRefType(GlobalConsts.APPLYAUTO_REFTYPE_AUTO_APPLY)
//                                    .setRequiredUnit(applyItem.getSkuUnit())
//                                    .setGmtUpdate(LocalDateTime.now())
//                                    .setSkuQtyApply(applyItem.getSkuQty())
//                                    .setGmtUpdate(LocalDateTime.now())
//                                    .setSkuQtyStock(10d)
//                                    .setSkuQtyApply(50d)
//                                    .setSkuQtyDaily(10d)
//                                    .setSkuQtySafety(30d)
//                                    .setRefId(null)
//                                    .setRefApplyItemId(applyItem.getId());
//                            applyAutos.add(applyAuto);
//                        });
//
//                        applyAutoService.saveBatch(applyAutos);
//                    }
//                }
//            }
//        });
//    }
//
//    //自动添加记账单
//    @Transactional(rollbackFor = Exception.class)
//    public void autoAddBills() {
//        List<Dept> depts = deptService.list(new QueryWrapper<Dept>().isNotNull("warehouse_id"));
//
//        if (depts == null || depts.size() == 0) {
//            return;
//        }
//
//        depts.forEach(dept -> {
//            Warehouse warehouse = warehouseService.getById(dept.getWarehouseId());
//            if (warehouse != null && StringUtils.isNotBlank(warehouse.getApplyWarehouseId())) {
//                List<Stock> stocks = stockService.list(new QueryWrapper<Stock>().eq("warehouse_id", warehouse.getId()).groupBy("supplier_id", "supplier_name"));
//                if (stocks != null && stocks.size() > 0) {
//                    stocks.forEach(stock -> {
//                        WorkOrder workOrder = new WorkOrder();
//                        List<WorkOrderItem> workOrderItems = Lists.newArrayList();
//                        workOrder.setBusDate(Calendar.getInstance().getTime())
//                                .setBusKey(serialRuleAdapter.getSerialRuleService().generateCode(SerialKeys.DEPT_USE_KEY))
//                                .setBusUser("system")
//                                .setDeptId(dept.getId())
//                                .setDeptName(dept.getName())
//                                .setRefId("0")
//                                .setRefKey("OUT0000000")
//                                .setSupplierId(stock.getSupplierId())
//                                .setSupplierName(stock.getSupplierName())
//                                .setBusType(WorkOrderType.OUT_USE)
//                                .setDirection(GlobalConsts.ORDER_DIRECTION_OUT)
//                                .setWarehouseId(warehouse.getId())
//                                .setWarehouseName(warehouse.getName())
//                                .setFlagOmoc(stock.getFlagOmoc())
//                                .setFlagConsignment(stock.getFlagConsignment())
//                                .setRemark("系统自动生成")
//                                .setFlowStatus("end")
//                        ;
//
//                        List<Stock> stocks1 = stockService.list(new QueryWrapper<Stock>().eq("warehouse_id", warehouse.getId()).eq("supplier_id", stock.getSupplierId()));
//                        stocks1.forEach(stock1 -> {
//                            WorkOrderItem workOrderItem = new WorkOrderItem();
//                            BeanUtils.copyProperties(stock1, workOrderItem);
//                            workOrderItem.setId(null);
//                            workOrderItem.setExpDate(stock1.getExpDate())
//                                    .setMatrId(stock1.getMatrId())
//                                    .setMatrName(stock1.getMatrName())
//                                    .setMatrSpec(stock1.getMatrSpec())
//                                    .setLot(stock1.getLot())
//                                    .setSkuPrice(stock1.getSkuPrice())
//                                    .setSkuQty(stock1.getSkuQty())
//                                    .setSkuUnit(stock1.getSkuUnit())
//                                    .setSkuQty(stock1.getSkuQty())
//                                    .setAmount(stock1.getAmount())
//                                    .setSn(stock1.getSn())
//                                    .setRfid(stock1.getRfid())
//                                    .setLocationId(stock1.getLocationId())
//                                    .setLocationName(stock1.getLocationName())
//                                    .setPackageQty(stock1.getPackageQty())
//                                    .setPackageUnit(stock1.getPackageUnit())
//                                    .setSterilizationDate(stock1.getSterilizationDate())
//                                    .setSterilizationIndate(stock1.getSterilizationIndate())
//                                    .setStockId(stock1.getId())
//                                    .setLineId(stock1.getLineId())
//                                    .setCertificateNo(stock1.getCertificateNo());
//                            workOrderItems.add(workOrderItem);
//                        });
//                        workOrder.setAmount(workOrderItems.stream().mapToDouble(WorkOrderItem::getAmount).sum());
//                        boolean saveResult = workOrderService.save(workOrder);
//                        if (saveResult) {
//                            workOrderItems.forEach(workOrderItem -> workOrderItem.setWorkOrderId(workOrder.getId()));
//                            workOrderItemService.saveBatch(workOrderItems);
//
//                            List<String> removeBillIds = billService.list(new QueryWrapper<Bill>().eq("dept_id", workOrder.getDeptId()).select("id")).stream().map(Bill::getId).collect(Collectors.toList());
//                            billService.remove(new QueryWrapper<Bill>().in("id", removeBillIds));
//                            billItemService.remove(new QueryWrapper<BillItem>().in("bill_id", removeBillIds));
//                            createBill(workOrder, workOrderItems);
//                        }
//                    });
//                }
//            }
//        });
//    }
//
//    /**
//     * 创建通用的记账单
//     *
//     * @param workOrder
//     * @return
//     */
//    private Bill _createCommonBill(WorkOrder workOrder) {
//        Bill bill = new Bill();
//        bill.setBusKey(serialRuleAdapter.getSerialRuleService().generateCode(SerialKeys.FINANCE_BILL_KEY));
//        bill.setBusDate(workOrder.getBusDate());
//        bill.setBusUser(workOrder.getBusUser());
//        bill.setAmount(workOrder.getAmount() * workOrder.getDirection());
//        bill.setSupplierId(workOrder.getSupplierId());
//        bill.setSupplierName(workOrder.getSupplierName());
//        bill.setDeptId(workOrder.getDeptId());
//        bill.setDeptName(workOrder.getDeptName());
//        bill.setFlagConsignment(workOrder.getFlagConsignment());
//        bill.setFlagOmoc(workOrder.getFlagOmoc());
//
//        //流程修改人、流程修改时间
//        bill.setFlowModifier(workOrder.getFlowModifier());
//        bill.setFlowModified(workOrder.getFlowModified());
//
//
//        return bill;
//    }
//
//    /**
//     * 创建通用的记账单明细表
//     *
//     * @param workOrderItems
//     * @return
//     */
//    private List<BillItem> _createCommonBillItem(String billId, List<WorkOrderItem> workOrderItems, Integer direction) {
//        List<BillItem> billItems = new ArrayList<>();
//        for (WorkOrderItem workOrderItem : workOrderItems) {
//            BillItem billItem = new BillItem();
//            BeanUtils.copyProperties(workOrderItem, billItem);
//            billItem.setId(null);
//            billItem.setBillId(billId);
//            billItem.setSkuQty(workOrderItem.getSkuQty() * direction);
//            billItem.setAmount(workOrderItem.getAmount() * direction);
//            billItems.add(billItem);
//        }
//
//        return billItems;
//    }
//
//    private void createBill(WorkOrder workOrder, List<WorkOrderItem> workOrderItems) {
//        if (WorkOrderType.WorkOrderTypeBillInAll.contains(workOrder.getBusType().toUpperCase())
//                || workOrder.getBusType().equalsIgnoreCase(WorkOrderType.OUT_SP)) {
//            // 购销的供应商入库单,退货出库单创建记账单，金额按照工单的direction来确定
//            // 代销的话，与记账单无关
//            if (!workOrder.getFlagConsignment()) {
//                Bill bill = _createCommonBill(workOrder);
//                bill.setFlagDept(false);
//                bill.setFlagSupplier(true);
//                bill.setFlowStatus(GlobalConsts.FLOW_END_VALUE); //记帐单直接已审核
//                billService.save(bill);
//                billItemService.saveBatch(_createCommonBillItem(bill.getId(), workOrderItems, workOrder.getDirection()));
//                log.info("工单{} - {} 已记帐，记帐金额：{}元", workOrder.getBusKey(), workOrder.getSupplierName(), bill.getAmount());
//            }
//        } else if (workOrder.getBusType().equalsIgnoreCase(WorkOrderType.OUT_USE)
//                ||workOrder.getBusType().equalsIgnoreCase(WorkOrderType.OUT_DIST)
//                ||workOrder.getBusType().equalsIgnoreCase(WorkOrderType.OPRT_USE)
//                ||workOrder.getBusType().equalsIgnoreCase(WorkOrderType.IN_USE_RED)  //冲红入库
//                || workOrder.getBusType().equalsIgnoreCase(WorkOrderType.IN_DEPT_RETURN)) {  // 科室退库
//            // 消耗出库和科室退货入库都创建记账单，因为肯定要计入科室成本；是否跟供应商有关，取决于代销标记
//            Bill bill = _createCommonBill(workOrder);
//            bill.setFlagDept(true);
//            bill.setFlagSupplier(workOrder.getFlagConsignment());
//            bill.setAmount(-bill.getAmount());  //出库记正值，入库记负值
//            bill.setFlowStatus(GlobalConsts.FLOW_END_VALUE); //记帐单直接已审核
//            billService.save(bill);
//            billItemService.saveBatch(_createCommonBillItem(bill.getId(), workOrderItems, -workOrder.getDirection()));
//            log.info("工单{} - {} 已记帐，记帐金额：{}元", workOrder.getBusKey(), workOrder.getSupplierName(), bill.getAmount());
//        }
//    }
//
//    //自动添加记账单
//    @Transactional(rollbackFor = Exception.class)
//    public void autoAddBillss() {
//        List<Dept> depts = deptService.list(new QueryWrapper<Dept>().isNotNull("warehouse_id"));
//
//        if (depts == null || depts.size() == 0) {
//            return;
//        }
//
//        depts.forEach(dept -> {
//            Warehouse warehouse = warehouseService.getById(dept.getWarehouseId());
//            if (warehouse != null && StringUtils.isNotBlank(warehouse.getApplyWarehouseId())) {
//                List<Stock> stocks = stockService.list(new QueryWrapper<Stock>().eq("warehouse_id", warehouse.getId()).groupBy("supplier_id", "supplier_name"));
//                if (stocks != null && stocks.size() > 0) {
//                    stocks.forEach(stock -> {
//                        Bill bill = new Bill();
//                        List<BillItem> billItems = Lists.newArrayList();
//                        bill.setBusDate(Calendar.getInstance().getTime())
//                                .setBusKey(serialRuleAdapter.getSerialRuleService().generateCode(SerialKeys.FINANCE_BILL_KEY))
//                                .setBusUser("system")
//                                .setDeptId(dept.getId())
//                                .setDeptName(dept.getName())
//                                .setSupplierId(stock.getSupplierId())
//                                .setSupplierName(stock.getSupplierName())
//                                .setExecDeptId(dept.getId())
//                                .setExecDeptName(dept.getName())
//                                .setFlagSupplier(false)
//                                .setFlagDept(true)
//                                .setFlagOmoc(stock.getFlagOmoc())
//                                .setFlagConsignment(stock.getFlagConsignment())
//                                .setRemark("系统自动生成")
//                                .setFlowStatus("end")
//                        ;
//
//                        List<Stock> stocks1 = stockService.list(new QueryWrapper<Stock>().eq("warehouse_id", warehouse.getId()).eq("supplier_id", stock.getSupplierId()));
//                        stocks1.forEach(stock1 -> {
//                            BillItem billItem = new BillItem();
//                            BeanUtils.copyProperties(stock1, billItem);
//                            billItem.setId(null);
//                            billItem.setExpDate(stock1.getExpDate())
//                                    .setMatrId(stock1.getMatrId())
//                                    .setMatrName(stock1.getMatrName())
//                                    .setMatrSpec(stock1.getMatrSpec())
//                                    .setLot(stock1.getLot())
//                                    .setSkuPrice(stock1.getSkuPrice())
//                                    .setSkuQty(stock1.getSkuQty())
//                                    .setSkuUnit(stock1.getSkuUnit())
//                                    .setSkuQty(stock1.getSkuQty())
//                                    .setAmount(stock1.getAmount())
//                                    .setSn(stock1.getSn())
//                                    .setRfid(stock1.getRfid());
//                            billItems.add(billItem);
//                        });
//                        bill.setAmount(billItems.stream().mapToDouble(BillItem::getAmount).sum());
//                        boolean saveResult = billService.save(bill);
//                        if (saveResult) {
//                            billItems.forEach(billItem -> billItem.setBillId(bill.getId()));
//                            billItemService.saveBatch(billItems);
//                        }
//                    });
//                }
//            }
//        });
//    }
//}
